package com.lyc.controller;

import com.lyc.entity.Category;
import com.lyc.entity.Color;
import com.lyc.entity.Product;
import com.lyc.entity.Size;
import com.lyc.entity.biz.PCSBiz;
import com.lyc.entity.qo.Conditions;
import com.lyc.entity.vo.PCS;
import com.lyc.entity.vo.ProductVo;
import com.lyc.service.ICategoryService;
import com.lyc.service.IProductService;
import com.lyc.service.ISolrService;
import com.lyc.utils.CollectionUtil;
import com.lyc.utils.UUIDUtil;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private IProductService productService;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private ISolrService solrService;

    @RequestMapping("getProductsByCid")
    public String getProductsByCid(int cid, Model model) {
        List<Category> categoryList = categoryService.getAll();
        List<Product> productList = productService.getProductsByCid(cid);
        model.addAttribute("productList", productList);
        model.addAttribute("categoryList", categoryList);
        model.addAttribute("totalCount", productList.size());
        model.addAttribute("cid", cid);
        return "/product/product_list";
    }

    @RequestMapping("getProductDetail")
    public String getProductDetail(int pid, Model model) {
        List<Category> categoryList = categoryService.getAll();
        Product product = productService.getProductByPidWithDesc(pid);
        ProductVo vo = new ProductVo();
        String description = product.getDescription();
        String[] strArr = description.split("&");
        if (strArr != null && strArr.length > 0) {
            product.setDescription(strArr[0]);
        }
        String[] pics = null;
        if (strArr != null && strArr.length > 1) {
            pics = strArr[1].split(";");
        }
        vo.setProduct(product);
        if (pics != null && pics.length > 0) {
            vo.setDesc_pics(Arrays.asList(pics));
        }
        model.addAttribute("product", vo);
        model.addAttribute("categoryList", categoryList);
        model.addAttribute("cid", product.getCid());
        return "/product/product_detail";
    }

    @RequestMapping("/search")
    public String search(Conditions conditions, Model model) {
        List<Category> categoryList = categoryService.getAll();
        List<Product> productList = null;
        try {
            productList = solrService.searchProducts(conditions);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
        model.addAttribute("productList", productList);
        model.addAttribute("categoryList", categoryList);
        return "/product/product_list";
    }

    @RequestMapping("/getHotSaleProduct")
    public String getHotSaleProduct(Model model) {
        try {
            List<Product> productList = solrService.getHotProducts();
            model.addAttribute("productList", productList);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
        return "/product/product_list_type";
    }

    @RequestMapping("/getNewProduct")
    public String getNewProduct(Model model) {
        try {
            List<Product> productList = solrService.getNewProducts();
            model.addAttribute("productList", productList);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
        return "/product/product_list_type";
    }

    @RequestMapping("/productList")
    public String productList(Conditions conditions, Model model) {
        List<Category> categoryList = categoryService.getAll();
        List<Product> productList = null;
        try {
            productList = solrService.searchProducts(conditions);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
        model.addAttribute("products", productList);
        model.addAttribute("categoryList", categoryList);
        model.addAttribute("conditions", conditions);
        return "/admin/product_list";
    }

    @RequestMapping("/delBatchByPids")
    public String delBatchByPids(Conditions conditions) {
        if (conditions != null) {
            if (CollectionUtil.notEmpty(conditions.getPids())) {
                productService.deleteBatchByPids(conditions.getPids());
            }
        }
        return "redirect:/product/productList";
    }

    @RequestMapping("/toAddProductPage")
    public String toAddProductPage(Model model, Integer pid) {
        if (pid != null) {
            Product product = productService.getProductByPid(pid);
            model.addAttribute("product", product);
        } else {
            model.addAttribute("today", new Date());
        }
        List<Category> categoryList = categoryService.getAll();
        model.addAttribute("categoryList", categoryList);
        return "/admin/product_add";
    }

    @RequestMapping("/addOrUpdateProduct")
    public String addOrUpdateProduct(Product product, MultipartFile picture, HttpServletRequest request, Model model) {
        String msg;
        try {
            if (picture != null && (picture.getOriginalFilename().endsWith(".png") || picture.getOriginalFilename().endsWith(".jpg") || picture.getOriginalFilename().endsWith(".gif"))) {
                String fileName = new String(picture.getOriginalFilename().getBytes("iso8859-1"), "utf-8");//中文转码
                String prefix = fileName.substring(fileName.lastIndexOf("."));//获取文件扩展名
                String name = UUIDUtil.getRandomFileName(prefix);
                picture.transferTo(new File(request.getServletContext().getRealPath("/static/images/goods/pics"), name));
                //如果该商品之前有图片则删除再设置新的图片
                File file = new File(request.getServletContext().getRealPath(product.getUrl()));
                if (file.exists())
                    file.delete();
                product.setUrl("/static/images/goods/pics/" + name);

                if (product == null || product.getPid() == null || product.getPid() <= 0) {
                    //添加操作，注意：使用solr不会自动生成主键，如果不设置主键则会空指针
                    product.setPid(productService.getPid());
                    productService.addProduct(product);
                } else {
                    //修改操作
                    Product p = productService.getProductByPidWithDesc(product.getPid());
                    String[] strArr = p.getDescription().split("&");
                    strArr[0] = product.getDescription();
                    product.setDescription(strArr[0] + "&" + strArr[1]);
                    productService.updateProduct(product);
                }
                return "redirect:/product/productList";
            } else if (picture == null && !StringUtils.isEmpty(product.getUrl())) {
                //如果没有上传图片且url存在路径则继续进行操作
                if (product == null || product.getPid() == null || product.getPid() <= 0) {
                    //添加操作
                    product.setPid(productService.getPid());
                    productService.addProduct(product);
                } else {
                    //修改操作
                    productService.updateProduct(product);
                }
                return "redirect:/product/productList";
            } else {
                msg = "仅支持.png/.jpg/.gif格式文件";
            }
        } catch (IOException e) {
            e.printStackTrace();
            msg = "文件上传失败";
        }
        String retUrl = request.getHeader("Referer");
        model.addAttribute("content", msg);
        model.addAttribute("url", retUrl);
        return "/common/errorModal";
    }

    @RequestMapping("/toAddDescPicsPage")
    public String toAddDescPicsPage(Integer pid, Model model) {
        Product product = productService.getProductByPidWithDesc(pid);
        String description = product.getDescription();
        List<String> desc_picList = null;
        if (!StringUtils.isEmpty(description)) {
            String[] strArr = description.split("&");
            if (strArr != null && strArr.length > 1) {
                if (!StringUtils.isEmpty(strArr[1])) {//有详情图片
                    String[] desc_pics = strArr[1].split(";");
                    desc_picList = Arrays.asList(desc_pics);
                }
            }
        }
        model.addAttribute("desc_pics", desc_picList);
        return "/admin/desc_pic_add";
    }

    @RequestMapping("/descPicsList")
    public String descPicsList(Integer type, Model model) {
        List<Category> categoryList = categoryService.getAll();
        List<Product> productList = null;
        try {
            productList = solrService.searchProducts(null);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
        model.addAttribute("products", productList);
        model.addAttribute("categoryList", categoryList);
        model.addAttribute("type", type);
        return "/admin/desc_pic_list";
    }

    @RequestMapping("/delDescPics")
    public String delDescPics(Integer pid, String pic, Model model) {
        if (!StringUtils.isEmpty(pic)) {
            //删除存储在服务器上的图片
            File picture = new File(pic);
            if (picture.exists())
                picture.delete();
            String p = ";" + pic;
            Product product = productService.getProductByPidWithDesc(pid);
            if (product != null) {
                String description = product.getDescription();
                if (!StringUtils.isEmpty(description)) {
                    String[] strArr = description.split("&");
                    if (strArr != null && strArr.length > 1) {
                        if (!StringUtils.isEmpty(strArr[1])) {
                            if (strArr[1].contains(p)) {
                                String pics = strArr[1].replace(p, "");
                                product.setDescription(strArr[0] + "&" + pics);
                                productService.updateProduct(product);
                                return "redirect:/product/toAddDescPicsPage?pid=" + pid;
                            } else if (strArr[1].contains(pic)) {
                                String pics = strArr[1].replace(pic, "");
                                product.setDescription(strArr[0] + "&" + pics);
                                productService.updateProduct(product);
                                return "redirect:/product/toAddDescPicsPage?pid=" + pid;
                            }
                        }
                    }
                }
            }
        }
        model.addAttribute("content", "图片删除失败");
        model.addAttribute("url", "/product/descPicsList");
        return "/common/errorModal";
    }

    //注意：多文件上传需要添加@RequestParam("pictures")注解，否则500
    //由于太做 导致varchar类型不够存储 需要把description字段该为text类型
    @RequestMapping("/addDescPics")
    public String addDescPics(Integer pid, @RequestParam("pictures") MultipartFile[] pictures, HttpServletRequest request, Model model) {
        try {
            if (pictures != null && pictures.length > 0) {
                int i = 0;
                for (MultipartFile picture : pictures) {
                    if (picture != null && (picture.getOriginalFilename().endsWith(".png") || picture.getOriginalFilename().endsWith(".jpg") || picture.getOriginalFilename().endsWith(".gif"))) {
                        String fileName = new String(picture.getOriginalFilename().getBytes("iso8859-1"), "utf-8");
                        if (!StringUtils.isEmpty(fileName)) {
                            String prefix = fileName.substring(fileName.lastIndexOf("."));
                            String randomFileName = UUIDUtil.getRandomFileName(prefix);
                            Product product = productService.getProductByPidWithDesc(pid);
                            String description = product.getDescription();
                            description += (description.endsWith(";") ? "/static/images/goods/desc/" : ";/static/images/goods/desc/" + randomFileName);
                            product.setDescription(description);
                            productService.updateProduct(product);
                            picture.transferTo(new File(request.getServletContext().getRealPath("/static/images/goods/desc"), randomFileName));
                        }
                    } else if (!StringUtils.isEmpty(picture.getOriginalFilename())) {
                        model.addAttribute("content", "仅支持.png/.jpg/.gif格式文件");
                        model.addAttribute("url", "/product/toAddDescPicsPage?pid=" + pid);
                        return "/common/errorModal";
                    }
                    i++;
                }
                model.addAttribute("content", "图片上传成功");
                model.addAttribute("url", "/product/toAddDescPicsPage?pid=" + pid);
                return "/common/errorModal";
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        model.addAttribute("content", "图片上传失败");
        model.addAttribute("url", "/product/toAddDescPicsPage?pid=" + pid);
        return "/common/errorModal";
    }

    @RequestMapping("/storeList")
    public String storeList(Model model) {
        List<Category> categoryList = categoryService.getAll();
        List<Product> productList = null;
        try {
            productList = solrService.searchProducts(null);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
        model.addAttribute("products", productList);
        model.addAttribute("categoryList", categoryList);
        return "/admin/store_list";
    }

    @RequestMapping("/toUpdateStore")
    public String toUpdateStore(Integer pid, Model model) {
        List<PCS> pcsList = productService.getPCSByPid(pid);
        model.addAttribute("pcsList", pcsList);
        return "/admin/store_update";
    }

    @RequestMapping("/updateStore")
    public String updateStore(Integer pid,PCSBiz biz, Model model) {
        String msg = productService.updateStore(biz);
        model.addAttribute("content", msg);
        model.addAttribute("url", "/product/toUpdateStore?pid=" + pid);
        return "/common/errorModal";
    }
}
